<script setup lang="tsx">
import { nextTick, ref } from 'vue';
import { $t } from '@/locales';
import type { ApiStateInput, ApiSysFilesOut, ApiSysFilesQuery, ApiUserOut, ApiUserQuery } from '@/api-services';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableOperate, useTableScroll } from '@/hooks/common/neto-table';
import { queryDone } from '@/utils/api';
import { UserApi } from '@/api-services/apis/user-api';
import Search from './modules/search.vue';
import OperateModal from './modules/operate-modal.vue';
import NImage from '@/components/file/image/n-image.vue';
import { SysfilesApi } from '@/api-services/apis/sysfiles-api';
import { GetThumbnailUrl } from '@/components/file/image/file-helper';

import message from 'element-plus/es/components/message';
//import Button from 'element-plus/es/components/button';
//import Popconfirm from 'element-plus/es/components/popconfirm';
//import Switch from 'element-plus/es/components/switch';
import { formatFileSize } from '@/utils/do-string';
import { ElSwitch, ElButton, ElPopconfirm } from 'element-plus';
const { tableWrapperRef, scrollConfig } = useTableScroll();


// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiSysFilesQuery) =>
  fetchTableQuery<ApiSysFilesQuery, ApiSysFilesOut>(params, (internalParams: ApiSysFilesQuery) =>
    getAPI(SysfilesApi).getList(internalParams)
  );

const loadingStates = ref<Record<string, boolean>>({});

const {
  columns,
  columnChecks,
  data,
  tableSize,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  size: 'small',
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    startDate: undefined,
    endDate: undefined,
    keyWords: ''
  },
  columns: () => [

    { type: 'selection', width: 48 },
    {
      prop: 'id',
      //dataIndex: 'id',
      label: 'id',
      align: 'center',
      minWidth: 130
    },
    {
      prop: 'fId',
      //dataIndex: 'fId',
      label: $t('page.fileManage.localFile.fid'),
      align: 'center',
      minWidth: 250
    },

    // 图片
    {
      //缩略图
      prop: 'imgfilepathThumbnail',
      //dataIndex: 'imgfilepathThumbnail',
      label: $t('page.fileManage.localFile.thumbnail'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (!record.fId) {
          return '';
        }
        const url = GetThumbnailUrl(record.fId);
        return (
          // <span>{record.fId}</span>
          <NImage url={url} maxHeight={100} maxWidth={100}></NImage>
        );
      }
    },
    {
      //文件名
      prop: 'name',
      //dataIndex: 'name',
      label: $t('page.fileManage.localFile.name'),
      align: 'center',
      minWidth: 300
    },
    {
      //文件大小
      prop: 'size',
      //dataIndex: 'size',
      label: $t('page.fileManage.localFile.fileSize'),
      align: 'center',
      minWidth: 100,
      formatter: record => {

        //计算文件大小
        const size = record.size;
        let sizeStr = '';
        if (size) {
          sizeStr = formatFileSize(size);
        }

        return (
          <span> {sizeStr}</span>
        );
      }
    },
    {
      //是否开放
      prop: 'isOpen',
      //dataIndex: 'isOpen',
      label: $t('page.fileManage.localFile.isOpen'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (!record.id) {
          return '';
        }
        const recordId = record.id;
        const handleSwitchChange = async (checked: boolean | string | number) => {

          loadingStates.value = {
            ...loadingStates.value,
            [recordId]: true
          };
          const [err, res] = await feature(getAPI(SysfilesApi).setIsOpen(recordId, !!checked));
          loadingStates.value = {
            ...loadingStates.value,
            [recordId]: false
          };
          queryDone(err, async () => {
            if (res?.data.data) {
              record.isOpen = !!checked;
              window.$message?.success($t('common.success'));
            } else {
              window.$message?.error($t('common.failed'));
            }
          })
        }
        return (
          <ElSwitch v-model={record.isOpen} onChange={handleSwitchChange} loading={loadingStates.value[recordId] || false} />
        );
      }
    },
    {
      prop: 'category',
      //dataIndex: 'category',
      label: $t('page.fileManage.localFile.category'),
      align: 'center',
      minWidth: 150
    },

    {
      //标签
      prop: 'tags',
      //dataIndex: 'tags',
      label: $t('page.fileManage.localFile.tags'),
      align: 'center',
      minWidth: 150
    },

    {
      //创建时间
      prop: 'creationTime',
      //dataIndex: 'creationTime',
      label: $t('common.creationTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //创建人
      prop: 'creatorUserName',
      //dataIndex: 'creatorUserName',
      label: $t('common.creatorUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      //修改时间
      prop: 'updateTime',
      //dataIndex: 'updateTime',
      label: $t('common.updateTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //修改人
      prop: 'updateUserName',
      //dataIndex: 'updateUserName',
      label: $t('common.updateUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },

    {
      prop: 'index',
      label: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      minWidth: 230,
      formatter: record => (
        <div class="flex-center gap-8px">
          <ElButton type="primary" plain size="small" onClick={() => edit(record.id!)}>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm onConfirm={() => handleDelete(record.id!)} title={$t('common.confirmDelete')}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const {
  isVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  editingId,
  handleOpen,
  checkedRowKeys,
  //rowSelection,
  onBatchDeleted,
  onDeleted

} = useTableOperate(data, getData);

const uploadRef = ref();
const uploadModalVisible = ref(false);
const handleUpload = () => {
  uploadModalVisible.value = true;
  nextTick(() => {
    if (uploadRef.value) {
      uploadRef.value.init();
    }
  });


};

const edit = (id: number) => {
  operateType.value = 'edit';
  handleEdit(id);
};
const handleDelete = async (id: number) => {
  const ids = [id];

  // 提交请求
  const [err, res] = await feature(getAPI(SysfilesApi).fakeDelete(id));

  queryDone(err, async () => {
    if (res?.data.data) {
      onDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
const handleBatchDeleted = async () => {
  if (!checkedRowKeys.value || checkedRowKeys.value.length == 0) {
    return;
  }
  const ids = checkedRowKeys.value.join(',');

  // 提交请求
  const [err, res] = await feature(getAPI(SysfilesApi).batchFakeDelete(ids));

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
const operateModalRef = ref()
const handleUploadSuccess = (id: number) => {
  operateType.value = 'edit';
  editingId.value = id;
  nextTick(() => {

    if (operateModalRef.value) {
      //重新加载
      operateModalRef.value.reloadFields();
    }
  })
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"></Search>
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.fileManage.titleList') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            v-model:size="tableSize" :show-table-size="true" :loading="loading" @add="handleAdd"
            @delete="handleBatchDeleted" @refresh="getData" />
        </div>

      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>
    </ElCard>
    <OperateModal ref="operateModalRef" v-model:visible="isVisible" :operate-type="operateType" :editing-id="editingId"
      @submitted="getDataByPage" @upload-success="handleUploadSuccess">
    </OperateModal>
  </div>
</template>

<style scoped></style>
